import { reqAddMajor, reqUpdateMajor } from "@/api/reqMajor";
import type { Major } from "@/types/major";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { reactive, ref, type Ref } from "vue";

export const addMajorsAndUpdateMajors = (changeRef: Ref<symbol>) => {
  const majorDialog = ref(false);

  const majorTitle = ref("");
  const majorForm = ref<Major>({
    majorname: "",
  });

  const formEle = ref<FormInstance>();

  const majorRules = reactive<FormRules<Major>>({
    majorname: [
      { required: true, message: "请输入专业名称", trigger: "blur" },
      {
        pattern: /^[\u4e00-\u9fa5]{2,8}$/,
        message: "专业名称必须为2到8个汉字",
        trigger: "blur",
      },
    ],
  });

  const addMajor = () => {
    majorTitle.value = "添加专业";
    majorDialog.value = true;
  };

  const updateMajor = (major: Major) => {
 majorForm.value = {
  ...major
 }
    majorTitle.value = "修改专业";
    majorDialog.value = true;
  };

  const addMajorSubmit = () => {
    console.log(formEle.value);
    formEle.value?.validate(async (isOk) => {
      if (isOk) {
        const { status, data, msg } = await reqAddMajor(majorForm.value);

        console.log(status);
        
        if (status === 0) {
          changeRef.value = Symbol();
          ElMessage.success("添加成功");
          close();
        } else {
          ElMessage.error(msg);
        }
      }
    });
  };

  const updateMajorSubmit = () => {
    formEle.value?.validate(async (isOk) => {
      if (isOk) {
        const { status, data, msg } = await reqUpdateMajor(majorForm.value);
        
        console.log(status);
        if (status === 0) {
          changeRef.value = Symbol();
          ElMessage.success("修改成功");
          close();
        } else {
          ElMessage.error(msg);
        }
      }
    });
  };
  const addOrUpdate = () => {
    if (majorTitle.value === "添加专业") {
      addMajorSubmit();
    } else {
      updateMajorSubmit();
    }
  };
  const close = () => {
    formEle.value?.resetFields();
    majorDialog.value = false;
  };

  return {
    majorDialog,
    majorForm,
    addMajor,
    majorTitle,
    majorRules,
    formEle,
    close,
    addMajorSubmit,
    updateMajorSubmit,
    updateMajor,
    addOrUpdate,
  };
};
